// import ol from 'ol' 
//地图渲染 及地图初始化方法
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import Map from 'ol/Map'
import {defaults} from 'ol/interaction'
import View from 'ol/View'
import {transform, transformExtent, fromLonLat, toLonLat} from 'ol/proj'
import MousePosition from 'ol/control/MousePosition'
import {format} from 'ol/coordinate'
import WKT from 'ol/format/WKT'
import WebGLPointsLayer from 'ol/layer/WebGLPoints'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import Style from 'ol/style/Style'
import Icon from 'ol/style/Icon'

import FeatureStyle from './FeatureStyle'

//变量
let map =null
let vectorWKT = null
let _this = this
let wktLayers = {}
let layers = {}
let mapURL = 'http://t{1-7}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=df5b7775fab31595f6c43caadb9af47d|http://t{1-7}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=df5b7775fab31595f6c43caadb9af47d'
// 底图 图层变量
let baseMapLayer = {
  // tileLayer: new ol.layer.Tile({
	tileLayer: new TileLayer({
    // source: new ol.source.XYZ({
		source: new XYZ({
      // crossOrigin: 'anonymous',
      url: mapURL.split('|')[0]
    })
  }),
  // labelLayer: new ol.layer.Tile({
	labelLayer: new TileLayer({
    zIndex: 1,
    // source: new ol.source.XYZ({
		source: new XYZ({
      // crossOrigin: 'anonymous',
      url: mapURL.split('|')[1]
    })
  })
}

//创建地图方法
//type：
function createMap(type) {
	console.log('createmap')
	let url = mapURL
	if(type) {
		map = null
		// map = new ol.Map({
		map = new Map({
			target: 'map',
			logo: false,
			layers: null,
			//默认双击不放大地图
			// interactions: ol.interaction.defaults({
			interactions: defaults({
				doubleClickZoom: false
			}),
			// view: new ol.View({
			view: new View({
				// center: ol.proj.transform([114.01884201049803, 22.621443705100845], 'EPSG:4326', 'EPSG:3857'),
				center: transform([114.01884201049803, 22.621443705100845], 'EPSG:4326', 'EPSG:3857'),
				zoom: 6
			}),
		})
	}else {
		map = null
		// map = new ol.Map({
		map = new Map({
			target: 'map',
			logo: false,
			layers: null,
			//默认双击不放大地图
			// interactions: ol.interaction.defaults({
			interactions: defaults({
				doubleClickZoom: false
			}),
			// view: new ol.View({
			view: new View({
				// center: ol.proj.transform([114.01884201049803, 22.621443705100845], 'EPSG:4326', 'EPSG:3857'),
				center: transform([114.01884201049803, 22.621443705100845], 'EPSG:4326', 'EPSG:3857'),
				zoom: 6,
				minZoom: 6,  
            	maxZoom: 18.5  
			}),
		})
		let temp = null
		// const mousePositionControl = new ol.control.MousePosition({
		const mousePositionControl = new MousePosition({
		  coordinateFormat: function (coordinate) {
		    temp = coordinate
		    // return ol.coordinate.format(coordinate, '经度:{x}°E 纬度:{y}°N', 2)
				return format(coordinate, '经度:{x}°E 纬度:{y}°N', 2)
		  },
		  projection: 'EPSG:4326',
		  className: 'ol-mouse-position',
		  target: document.getElementById('mouse-position'),
		})
		map.addControl(mousePositionControl)// 实例化坐标拾取控件，并加入地
		map.addLayer(baseMapLayer.tileLayer) //矢量图
		map.addLayer(baseMapLayer.labelLayer) //影像图
	}
	// 监听地图缩放，
	map.on('moveend', function(e) {
		console.log('当前地图层级', map.getView().getZoom())
	})
	// 监听地图单击
	map.on('singleclick', evt => {
		console.log(evt.coordinate)
		if (vueContent.$store.state.mainFrame.isShowExceptionPanel && !vueContent.$store.state.indexAlertState.isShowAddException) {
			console.log('点击了异常地图')
			vueContent.$store.state.identifyImgGeom = transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326') // 点坐标
			console.log('鼠标坐标', vueContent.$store.state.identifyImgGeom)
			judgeInit(evt.coordinate)
			vueContent.$store.state.isClickMap = !vueContent.$store.state.isClickMap
		}
	})
	
}




function judgeInit (coordinate) {
	vueContent.$store.state.currentArea.forEach(area => {
		if(area.area_geom) {
			let WTKFormat = new WKT();//坐标系转换
			let featurepolygon = WTKFormat.readFeature(area.area_geom, {
			    dataProjection: 'EPSG:4326',
			    featureProjection: 'EPSG:3857'
			  })//将4326的WKT格式转geoJson
			if(featurepolygon.getGeometry().intersectsCoordinate(coordinate)) {
				localStorage.setItem('areaname', area.area_name)
				console.log(area.area_name)
			}//保存面名称
		}
	})
	let isin = true
	let inindex = null
	if(vueContent.$store.state.polygonStr[0]) {
		for(let index = 0; index < vueContent.$store.state.polygonStr.length; index++) {
			let WTKFormat = new WKT()
			let featurepolygon = WTKFormat.readFeature(vueContent.$store.state.polygonStr[index], {
			    dataProjection: 'EPSG:4326',
			    featureProjection: 'EPSG:3857'
			  })
			if(featurepolygon.getGeometry().intersectsCoordinate(coordinate) === isin) {
				isin = false
				inindex = index
				break
			}
		}
		if(!isin) {
			console.log(inindex, '在里面')
			if(vueContent.$store.state.RDCIndex || vueContent.$store.state.RDCIndex === 0) {
					vueContent.$mapOperation.removeWKT(vueContent.$store.state.polygonStr[vueContent.$store.state.RDCIndex])
					vueContent.$mapOperation.removeWKT(vueContent.$store.state.polygonStr[vueContent.$store.state.RDCIndex + 1])
				}
				vueContent.$store.state.RDCNum = Number(inindex) + 1
				vueContent.$store.state.isShowLeidaGeom = true
				vueContent.$store.state.RDCIndex = Number(inindex)
				vueContent.$mapOperation.drawWKT(vueContent.$store.state.polygonStr[inindex], 5)
			}else {
				// vueContent.$store.state.RDCIndex = null
				vueContent.$mapOperation.removeWKT(vueContent.$store.state.polygonStr[inindex])
				
				vueContent.$store.state.isShowLeidaGeom = false
				vueContent.$store.state.RDCNum = 1
				vueContent.$store.state.RDCRow = 1
				vueContent.$store.state.RDCCol = 1
			}
	}else {
		vueContent.$store.state.isShowLeidaGeom = false
		vueContent.$store.state.RDCNum = 1
		vueContent.$store.state.RDCRow = 1
		vueContent.$store.state.RDCCol = 1
		// vueContent.$store.state.polygonStr = []
	}
}

export default {
	judgeInit,
	createMap(type) {
		map = null
		createMap(type)
		return map
	},
	getMap() {
		if(map === null){
			if(vueContent.$store.state.mainFrame.isShowExceptionPanel) {
				createMap(1)
			}else {
				createMap()
			}
		}
		return map
	},
	// 设置底图 地图切换
	setBaseMap (layer) {
		map.removeLayer(baseMapLayer.tileLayer)
		map.removeLayer(baseMapLayer.labelLayer)

	  let source = null
	  let type = layer.typeName
	  let url = layer.url
	  let labelSource = baseMapLayer.labelLayer.getSource()
	  if (labelSource) {
	    baseMapLayer.labelLayer.setSource(null)
	  }
	  if (type === 'tianditu' || type === 'xyz') {
	    source = new XYZ({
	      // crossOrigin: 'anonymous',
	      url: url.split('|')[0]
	    })
	    let labelSource = new XYZ({
	      // crossOrigin: 'anonymous',
	      url: url.split('|')[1]
	    })
		baseMapLayer.labelLayer.setZIndex(-1)
	    baseMapLayer.labelLayer.setSource(labelSource)
	  }
	  baseMapLayer.tileLayer.setSource(source)
		baseMapLayer.tileLayer.setZIndex(-2)
		map.addLayer(baseMapLayer.tileLayer)
		map.addLayer(baseMapLayer.labelLayer)
		map.index = -1
	},
	// // 添加网格图层
	// drawGraticule(geometry, intervalsNum) {
	// 	let graticule = new ol.layer.Graticule({
	// 	    opacity:1,//透明度，默认为1
	// 	    visible:true,//是否显示，默认true
	// 	    zIndex:1,//图层渲染的Z索引,默认按加载顺序叠加
	// 			intervals: [intervalsNum],
	// 	    extent: ol.proj.transformExtent(geometry, 'EPSG:4326', 'EPSG:3857'),//渲染范围，默认是渲染全部
	// 	    targetSize:100,//单元格像素大小,默认100
	// 	    showLabels:true,//为每条刻度线绘制一个带有各自纬度/经度的标签,默认true
	// 	    strokeStyle: new ol.style.Stroke({//用于绘制刻度线的样式
	// 	        color: 'rgba(255,0,0,1)',//线条颜色
	// 	        width: 2,//线条宽度
	// 	        lineDash: [4]//虚线模式，默认值为null，无虚线
	// 	    })
	// 	})
	// 	this.getMap().addLayer(graticule)
	// 	console.log(graticule.getExtent())
	// },
	drawWKT (geomstring, style) {
		let wkt = geomstring
		// console.log(wkt)
		this.removeWKT(wkt)
		let format = new WKT()
		let feature = format.readFeature(wkt,{
			dataProjection: 'EPSG:4326',
			featureProjection: 'EPSG:3857'
		})
		// console.log(feature)
		if (style === 5) {
			vectorWKT = FeatureStyle.getStrokeAnimationStyle(feature)
		}
		// else if(style === 'ICON') {
		// 	let coordA = wkt.split('(')
		// 	let coordB = coordA[1].split(')')
		// 	let coordC = coordB[0].split(',')
		// 	let coordD = coordC[0].split(' ')
		// 	let coordinate = []
		// 	coordD.forEach(item => {
		// 		coordinate.push(Number(item))
		// 	})
		// 	let coordinates = transform(coordinate, 'EPSG:4326', 'EPSG:3857')
		// 	// transformExtent(coordinate, 'EPSG:4326', 'EPSG:3857')
		// 	feature = new Feature({
  //       type: 'icon',
  //       geometry: new Point(coordinates)
  //     })
		// 	console.log(coordinates)
		// 	vectorWKT = new VectorLayer({
		// 		source: new VectorSource({
		// 			features: [feature]
		// 		}),
		// 		style: FeatureStyle.getStyle(style)
		// 	})
		// }
		else {
			vectorWKT = new VectorLayer({
				source: new VectorSource({
					features: [feature]
				}),
				style: FeatureStyle.getStyle(style)
			})
		}
		wktLayers[wkt] = vectorWKT
		
		this.getMap().addLayer(vectorWKT)
	}, 
	getWktLayer (wkt) {
	  let wktLayer = wktLayers[wkt]
	  return wktLayer
	},
	removeWKT (wkt) {
		let wktLayer = this.getWktLayer(wkt)
		if(wktLayer) {
			this.getMap().removeLayer(wktLayer)
			delete wktLayers[wkt]
		}
	},
	clearWKT () {
		Object.keys(wktLayers).forEach(key => {
		  this.getMap().removeLayer(wktLayers[key])
		  delete wktLayers[key]
		})
	},
	// 将3857投影的Feature或Geometry转为wtk字符串
	transformToWKT (feature) {
	  let WTKFormat = new WKT()
	  let wktStr = ''
	  // 说明是geometry
	  if (feature.layout) {
	    wktStr = WTKFormat.writeGeometry(feature, {
	      dataProjection: 'EPSG:4326',
	      featureProjection: 'EPSG:3857'
	    })
	  } else {
	    wktStr = WTKFormat.writeFeature(feature, {
	      dataProjection: 'EPSG:4326',
	      featureProjection: 'EPSG:3857'
	    })
	  }
	  return wktStr
	},
	// 读取WKT字符串，转为geom（0）或feture（1）
	readWKTtoFeature (wktStr, type) {
	  let WTKFormat = new WKT()
	  if (type === 0) {
	    return WTKFormat.readGeometry(wktStr, {
	      dataProjection: 'EPSG:4326',
	      featureProjection: 'EPSG:3857'
	    })
	  } else {
	    return WTKFormat.readFeature(wktStr, {
	      dataProjection: 'EPSG:4326',
	      featureProjection: 'EPSG:3857'
	    })
	  }
	},
	getExtent() {
		return this.projectCoordinate(map.getView().calculateExtent(map.getSize()), 1)
	},
	// 缩放到指定范围
	zoomToExtent(featurewkt) {
		let feature = this.readWKTtoFeature(featurewkt, 1)
		this.zoomToExtentOrGeom(feature.getGeometry())
		this.extent = this.projectCoordinate(feature.getGeometry().getExtent(), 1).join()
	},
	// 缩放到extent或geometry
	zoomToExtentOrGeom (extent, callback) {
		if(vueContent.$store.state.mainFrame.isShowExceptionPanel) {
			this.getMap()
			  .getView()
			  .fit(extent, {
			    duration: 1000,
			    callback: callback
			  })
		}else {
			this.getMap()
			  .getView()
			  .fit(extent, {
			    duration: 1000,
			    callback: callback,
					maxZoom: 18,
			  })
		}
	  
	},
  // 坐标转换(点和extent)，type：0为4326转3857，1为3857转4326
  	projectCoordinate (coordinates, type) {
    if (coordinates.length === 4) {
      if (type === 0) {
        return transformExtent(coordinates, 'EPSG:4326', 'EPSG:3857')
      } else {
        return transformExtent(coordinates, 'EPSG:3857', 'EPSG:4326')
      }
    } else {
      if (type === 0) {
        return fromLonLat(coordinates)
      } else if (type === 1) {
        return toLonLat(coordinates)
      }
    }
  },
  /**
   * 将一维数组转成二维可用范围extent
   * @param extent
   * @returns {number[][][]}
   * @constructor
   */
  	extentConversion (extent) {
    let minX = parseFloat(extent[0])
    let minY = parseFloat(extent[1])
    let maxX = parseFloat(extent[2])
    let maxY = parseFloat(extent[3])
    let flatCoordinate =
      [[[minX, minY], [minX, maxY], [maxX, maxY], [maxX, minY], [minX, minY]]]
    return flatCoordinate
  },
	// 添加VectorLayer
	addVectorLayer (catID, layerID) {
		let vectorLayer = new VectorLayer({
		  source: new VectorSource(),
		  style: FeatureStyle.defaultStyle
		})
		map.addLayer(vectorLayer)
		let layer = this.getLayer(catID, layerID)
		if (layer) {
		  this.getMap().removeLayer(layer)
		}
		layers['layer_' + catID + '_' + layerID] = vectorLayer
		return vectorLayer
	},
  /**
   * 删除图层
   * @param catID {string}
   * @param layerID {string}
   * @returns {ol.layer.Image}
   */
  removeLayer (catID, layerID) {
    const layer = this.getLayer(catID, layerID)
    if (layer) {
      map.removeLayer(layer)
      delete layers['layer_' + catID + '_' + layerID]
    }
    return layer
  },
  // 获取指定的图层，未找到返回null
  getLayer (catID, layerID) {
    let layer = layers['layer_' + catID + '_' + layerID]
    return layer
  }
}